// pages/goodsList/goodsList.js
const {
  loadGoddsByShopClassify,
  getAllProductByLabel,
  findGoodsByPlatform
} = require('../../api/url')
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    priceState: 'down', //价格升序或降序 'up' 'down'
    showModel: false, //显示分类框
    currentFilter: '', //目前筛选标签 17：全部 2：新品 3：热卖 
    showFilterModel: false, //是否显示筛选框
    currentType: '', //目前是从哪个入口跳转进来的
    currentSort: 'gen', //目前排序标签
    isSearch: false, //是否处于搜索状态
    searchKeyWord: '', //搜索关键字
    shopId: '', //店铺id
    page: 1,
    loadOver: false,
    size: 20,
    goodsList: [], //商品列表
    showGoodsList: [], //展示商品列表
    options: null,
    headerHeight: 0, //头部高度
  },
  /**
   * @method
   * @desc 加顶部padding
   */
  setPadding(e) {
    let that = this
    that.setData({
      headerHeight: e.detail
    })
  },
  /**
   * @method
   * @desc 搜索商品
   */
  search(e) {
    let that = this
    let value = e.detail.value
    that.setData({
      searchKeyWord: value,
      isSearch: true
    })
    that.setData({
      priceState: 'down', //价格升序或降序 'up' 'down'
      showModel: false, //显示分类框
      currentFilter: '', //目前筛选标签 17：全部 2：新品 3：热卖 
      showFilterModel: false, //是否显示筛选框
      currentSort: 'gen', //目前排序标签
      page: 1,//页码
      loadOver: false,//是否加载完商品
      size: 20,//每页数据量
      goodsList: [], //商品列表
      showGoodsList: [], //展示商品列表
    })
    wx.showLoading({
      title: '搜索中',
      mask: true
    })
    wx.request({
      url: getAllProductByLabel,
      data: {
        page: that.data.page,
        size: that.data.size,
        fName: value
      },
      success(res) {
        wx.hideLoading()
        that.doResponse(res)
      },
      fail() {
        wx.hideLoading()
        wx.showToast({
          title: '搜索商品异常',
          icon: 'none'
        })
      }
    })
  },
  /**
   * @method
   * @desc 确认或取消筛选
   */
  doFilterAction(e) {
    let type = e.currentTarget.dataset.type
    this.setData({
      showFilterModel: !this.data.showFilterModel
    })
    if (type === 'confirm') {
      this.filterGoods(this.data.currentFilter)
    } else {
      this.setData({
        currentFilter: ''
      })
    }
  },
  /**
   * @method
   * @param filterType 筛选关键字
   * @desc 筛选商品
   */
  filterGoods(filterType) {
    let that = this,
      temList = that.data.goodsList
    if (filterType === '17') {
      that.setData({
        showGoodsList: temList
      })
    } else {
      temList = temList.filter(val => {
        return val.fLabel.indexOf(filterType)!=-1
      })
      that.setData({
        showGoodsList: temList
      })
    }
  },

  /**
   * @method
   * @desc 切换筛选选项
   */
  toggleFilter(e) {
    this.setData({
      currentFilter: e.currentTarget.dataset.filtertype
    })
  },
  /**
   * @method
   * @desc 切换显示分类
   */
  showModel() {
    this.setData({
      showModel: !this.data.showModel,
    })
  },
  /**
   * @method
   * @desc 切换排序
   */
  toggleSort(e) {
    let that = this
    let type = e.currentTarget.dataset.type
    switch (type) {
      case 'gen':
        that.setData({
          currentSort: 'gen',
          priceState: 'down',
          showGoodsList: that.data.goodsList,
          currentFilter: ''
        })
        break
      case 'sale':
        that.setData({
          currentSort: 'sale',
          priceState: 'down'
        })
        let temGoodsList = that.data.showGoodsList
        temGoodsList.sort(function(x, y) {
          if (x.fTotalSales != null && y.fTotalSales != null && x.fTotalSales != undefined && y.fTotalSales != undefined) {
            if (x.fTotalSales < y.fTotalSales) {
              return 1
            } else if (x.fTotalSales == y.fTotalSales) {
              return 0
            } else {
              return -1
            }
          } else {
            return 0
          }
        })
        that.setData({
          showGoodsList: temGoodsList
        })
        break
      case 'price':
        that.setData({
          currentSort: 'price',
          priceState: that.data.priceState == 'up' ? 'down' : 'up'
        })
        if (that.data.priceState == 'down') {
          let temGoodsList = that.data.showGoodsList
          temGoodsList.sort(function(x, y) {
            if (x.fFixedPrice != null && y.fFixedPrice != null && x.fFixedPrice != undefined && y.fFixedPrice != undefined) {
              if (x.fFixedPrice < y.fFixedPrice) {
                return 1
              } else if (x.fFixedPrice == y.fFixedPrice) {
                return 0
              } else {
                return -1
              }
            } else {
              return 0
            }

          })
          that.setData({
            showGoodsList: temGoodsList
          })
        } else {
          let temGoodsList = that.data.showGoodsList
          temGoodsList.sort(function(x, y) {
            if (x.fFixedPrice != null && y.fFixedPrice != null && x.fFixedPrice != undefined && y.fFixedPrice != undefined) {
              if (x.fFixedPrice < y.fFixedPrice) {
                return -1
              } else if (x.fFixedPrice == y.fFixedPrice) {
                return 0
              } else {
                return 1
              }
            } else {
              return 0
            }

          })
          that.setData({
            showGoodsList: temGoodsList
          })
        }
        break
      case 'filter':
        that.setData({
          currentSort: 'filter',
          priceState: 'down',
          showFilterModel: true
        })
        break
    }
  },
  /**
   * @method
   * @desc 跳转商品详情页
   */
  goGoodsDetail(e) {
    wx.navigateTo({
      url: '../goodsDetail/goodsDetail?id=' + e.currentTarget.dataset.id
    })
  },
  /**
   * @method
   * @desc 处理响应
   */
  doResponse(res) {
    let that = this
    if (res.data.code === 0) {
      that.setData({
        page: that.data.page + 1
      })
      let temList = res.data.response.cont.list
      if (temList && temList.length > 0) {
        if (temList.length < that.data.size) {
          that.setData({
            loadOver: true
          })
          wx.showToast({
            title: '已加载完商品',
            icon: 'none'
          })
        }
        temList.forEach(val => {
          val.img = app.globalData.imageBaseUrl + val.fMainPicture
          val.priceTxt = val.fFixedPrice.toFixed(2)
          val.originalPri = val.fBuyingPrice.toFixed(2)
        })
        that.setData({
          goodsList: that.data.goodsList.concat(temList),
          showGoodsList: that.data.goodsList.concat(temList)
        })
      } else {
        that.setData({
          loadOver: true
        })
        wx.showToast({
          title: '已加载完商品',
          icon: 'none'
        })
      }
    }
  },
  /**
   * @method
   * @desc 根据店铺查商品
   */
  loadGoddsByShopClassify(page, size, id) {
    let that = this
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    wx.request({
      url: findGoodsByPlatform,
      data: {
        page,
        size,
        fPlatformCategoryId: id
      },
      success(res) {
        wx.hideLoading()
        that.doResponse(res)
      }
    })
  },
  /**
   * @method
   * @desc 加载搜索商品
   */
  loadSearchGoods() {
    let that = this
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    wx.request({
      url: getAllProductByLabel,
      data: {
        page: that.data.page,
        size: that.data.size,
        fName: that.data.searchKeyWord
      },
      success(res) {
        wx.hideLoading()
        that.doResponse(res)
      },
      fail(){
        wx.showToast({
          title: '加载搜索商品异常',
          icon:'none'
        })
        wx.hideLoading()
      }

    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    let that = this
    let type = options.type
    that.setData({
      currentType: type
    })
    switch (that.data.currentType) {
      case "shopClassfy":
        let id = options.id
        that.setData({
          shopId: id
        })
        that.loadGoddsByShopClassify(that.data.page, that.data.size, id)
        break
      case 'search':
        let keyWord = options.keyWord
        that.setData({
          searchKeyWord: keyWord,
          isSearch: true
        })
        that.loadSearchGoods()
        break
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    let that = this
    that.setData({
      priceState: 'down', //价格升序或降序 'up' 'down'
      currentFilter: '', //目前筛选标签 17：全部 2：新品 3：热卖 
      showFilterModel: false, //是否显示筛选框
      currentSort: 'gen', //目前排序标签
      isSearch: false, //是否处于搜索状态
      searchKeyWord: '', //搜索关键字
      page: 1,
      loadOver: false,
      size: 20,
      goodsList: [], //商品列表
      showGoodsList: [], //展示商品列表
      options: null,
    })
    switch (that.data.currentType) {
      case "shopClassfy":
        that.loadGoddsByShopClassify(that.data.page, that.data.size, that.data.shopId)
        setTimeout(wx.stopPullDownRefresh, 500)
        break
      case 'search':
        that.loadSearchGoods()
        setTimeout(wx.stopPullDownRefresh, 500)
        break
    }
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    let that = this
    if (!that.data.loadOver) { //如果没有加载完
      if (that.data.isSearch) { //如果是搜索商品
        that.loadSearchGoods()
      } else { //如果不是搜索商品
        switch (that.data.currentType) {
          case "shopClassfy":
            that.loadGoddsByShopClassify(that.data.page, that.data.size, that.data.shopId)
            break
        }
      }
    }else{
      wx.showToast({
        title: '没有啦',
        icon:'none'
      })
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})